const mongoose = require('mongoose');
const Counter = require('./counter');
const dayjs = require('dayjs');
const { Schema } = mongoose

const MenuSchema = new Schema({
  menu_id: {
    type: Number,
    unique: true,
    description: '菜单id'
  },
  name: {
    type: String,
    unique: true,
    required: true,
    description: '菜单名称'
  },
  code: {
    type: String,
    unique: true,
    required: true,
    description: '菜单编码，用于系统标识'
  },
  path: {
    type: String,
    required: true,
    description: '菜单路径'
  },
  description: {
    type: String, 
    required: false,
    description: '菜单描述',
    default: ''
  },
  parent_id: {
    type: Number,
    default: null,
    description: '父菜单id，顶级菜单为null'
  },
  level: {
    type: Number,
    required: false,
    default: 1,
    description: '菜单层级，从1开始'
  },
  sort_order: {
    type: Number,
    default: 0,
    description: '排序号，值越小越靠前'
  },
  icon: {
    type: String,
    required: false,
    description: '菜单图标',
    default: ''
  },
  is_visible: {
    type: Boolean,
    default: true,
    description: '是否可见'
  },
  created_at: {
    type: String, 
    default: dayjs().format('YYYY-MM-DD HH:mm:ss'),
    description: '创建时间'
  },
  updated_at: {
    type: String, 
    default: dayjs().format('YYYY-MM-DD HH:mm:ss'),
    description: '最后更新时间'
  },
  created_by: {
    type: Number,
    default: null,
    description: '创建者id'
  },
  updated_by: {
    type: Number,
    default: null,
    description: '最后更新者id'
  }
})

MenuSchema.pre('save', async function(next) {
  if(this.isNew) {
    try {
      const counter = await Counter.findByIdAndUpdate(
        { _id: 'menu_id' },
        { $inc: { seq: 1 } },
        { new: true, upsert: true }
      );
      this.menu_id = counter.seq;
      next();
    } catch (error) {
      next(error);
    }
  } else {
    next();
  }
});

MenuSchema.pre('updateOne', async function(next) {
  this.set({ updated_at: dayjs().format('YYYY-MM-DD HH:mm:ss') });
  next();
});

const menuModel = mongoose.model('menu', MenuSchema, 'menu')

module.exports = menuModel